//! 结构体join实现
//! 
//! 用于仅存放连接字段，无关联结构体的join
//! 不生产相关方法，仅生成相关sql
//! 
//! 例如：
//! 
//! ```ignore
//! #[orm_join(
//! select_field="node.name AS node_name, organization.name AS org_name",
//! join="JOIN node ON node.id = node_id JOIN organization ON organization.id = node.org_id",
//! )]
//! struct user {
//!     id:u32,
//!     name:String,
//!     /// 所属网点：连接到其他表
//!     node_id:String,
//! }
//! ```
//! 
use syn::{
    Lit, Meta, MetaList, MetaNameValue,
    NestedMeta,
};
/// 结构体join信息
pub struct StructJoinInfo{
    pub select_field:String,
    pub join:String,
}

/// 实现struct的join
pub(super) fn parse_struct_orm_join(ast: &syn::DeriveInput) -> Vec<StructJoinInfo> {
    // 解析 orm_join
    let mut struct_join_infos = Vec::new();
    for orm_struct_attrs in  ast.attrs.iter().filter_map(|attr| {
        if attr.path.is_ident("orm_join") {
            attr.parse_meta().ok().map(|meta| {
                if let Meta::List(MetaList{nested,..}) = meta{
                    let args:Vec<_> = nested.iter().filter_map(|nested_meta|{
                        if let NestedMeta::Meta(Meta::NameValue(MetaNameValue{path,lit,..})) = nested_meta{
                            let name = path.get_ident().unwrap().to_string();
                            if path.is_ident("select_field") || path.is_ident("join"){
                                match lit{
                                    Lit::Str(lit_str) => Some((name,lit_str.value())),
                                    _ => panic!("结构体 orm_join 参数说明,正确参数为:select_field,join"),
                                }
                            }else{
                                None
                            }
                        }else{
                            None
                        }
                    }).collect();
                    args
                }else{
                    panic!("orm_join 属性设置错误")
                }
            })
        } else {
            None
        }
    }){
        // 获取 select_field
        let select_field = orm_struct_attrs.iter().find_map(|(name,value)| (name=="select_field")
            .then_some(value)).expect("获取join select_field");
        // 获取 select_field
        let join = orm_struct_attrs.iter().find_map(|(name,value)| (name=="join")
            .then_some(value)).expect("获取join");
        struct_join_infos.push(StructJoinInfo{
            select_field:select_field.to_owned(),
            join:join.to_owned()
        });
    }
    struct_join_infos
}